<template>
  <el-upload
    v-if="action"
    :action="action"
    :file-list="list"
    :list-type="type"
    :multiple="multiple"

    :limit="limit"
    :on-change="change"
    :on-remove="remove"
    :on-exceed="exceed"
    :before-upload="before"
  >
    <el-button size="small" :disabled="disabled" type="primary" v-text="`选择${txt}`" />
    <div slot="tip" class="el-upload__tip" v-text="cfg.tip" />
  </el-upload>
  <el-alert v-else title="当前项目没有配置 fileServer 或 fileToken, 所以上传组件无法正常使用" type="error" :closable="false" />
</template>
<script>
import { Upload as elUpload, Button as elButton, Alert as elAlert } from 'element-ui'
import control from '@/mixins/control'

export default {
  components: { elUpload, elButton, elAlert },
  mixins: [control],
  computed: {
    action() {
      const { fileServer } = window.config
      if (fileServer) {
        return `${fileServer}`
      } else {
        return null
      }
    },
    cfg() {
      return this.config || {}
    },
    type() {
      return this.cfg.isImg ? 'picture' : 'text'
    },
    disabled() {
      return this.cfg.disabled || false
    },
    txt() {
      return this.cfg.isImg ? '图片' : '附件'
    },
    multiple() {
      return this.cfg.limit > 1
    },
    limit() {
      return this.cfg.limit || 0
    },
    list: {
      set(val) {
        this.val = val
      },
      get() {
        if (this.val) {
          return this.val.map(r => {
            if (r.absolutePath) {
              return {
                name: r.name || `tmp_${Math.random()}`,
                url: r.absolutePath,
                code: r.code
              }
            } else {
              return r
            }
          })
        } else {
          return []
        }
      }
    },
    returnValue() {
      return this.list.map(r => {
        if (r.response) {
          return {
            name: r.response.data.name,
            path: r.response.data.path,
            code: r.response.data.code
          }
        } else {
          return {
            name: r.name,
            path: r.url,
            code: r.code
          }
        }
      })
    }
  },
  created() {
    if (this.value === null || typeof this.value === 'undefined') {
      this.val = []
    } else {
      this.val = this.value
    }
  },
  methods: {
    remove(r, fileList) {
      if (r && r.status === 'success') {
        this.list = fileList
      }
    },
    change(r, fileList) {
      if (r.response) {
        const { code, data, message } = r.response
        if (code * 1 === 200 && data) {
          if (this.limit <= 1) {
            this.list = fileList.slice(-1)
          } else {
            this.list = fileList
          }
        } else {
          window.$$.msg.error(message)
          fileList.pop()
        }
      } else if (!r) {
        window.$c.error(r)
      }
    },
    // 上传前的处理
    before() {},
    exceed() {
      window.$$.msg.error(`超出限制, 最多只能上传${this.limit}个文件`)
    }

  }
}
</script>
